package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //SpringMVC中 已经自动创建了HttpSession对象放入在IOC容器中管理  使用时可以直接注入的
    //@Autowired
    //private HttpSession session;

    //新增时设置公共字段的值
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler...："+Thread.currentThread().getId());
        //从session中获取当前登录的用户id
        //Long id = (Long) session.getAttribute("employee");
        Long id = BaseContext.getCurrentId();

        //createUser createTime updateUser updateTime
        log.info("========公共字段填充【新增】========");
        metaObject.setValue("createUser",id);
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateUser",id);
        metaObject.setValue("updateTime",LocalDateTime.now());
    }

    //修改时设置公共字段的值
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler...："+Thread.currentThread().getId());

        //从session中获取当前登录的用户id
        //Long id = (Long) session.getAttribute("employee");
        Long id = BaseContext.getCurrentId();

        //updateUser updateTime
        log.info("========公共字段填充【修改】========");
        metaObject.setValue("updateUser",id);
        metaObject.setValue("updateTime",LocalDateTime.now());

    }
}
